package com.easycoding.framework.web.filter;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easycoding.framework.web.response.ResponseWrapper;

public class CreateHtmlFilter implements Filter {

	protected FilterConfig config;
	private String htmlPath;
	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse) response;
		ResponseWrapper wrapper = new ResponseWrapper(res);
		//pass the request along the filter chain
		chain.doFilter(request, wrapper);

		wrapper.getWriter().flush();
		
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		//TODO linxx 根据实际的情况生成静态网页
		File htmlFile = new File(htmlPath,uri);
		if (!htmlFile.exists()) {
			htmlFile.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(htmlFile);
		DataOutputStream dos = new DataOutputStream(fos);
		dos.writeUTF(wrapper.getContent());
		dos.close();
		fos.close();
		//定向到静态文件
		//request.getRequestDispatcher(uri).forward(request, response);
	}

	public void init(FilterConfig config) throws ServletException {
		System.out.println("init filter:"+config.getFilterName()+"...");
		String webRealPath = config.getServletContext().getRealPath("/");
		System.out.println("application path="+webRealPath);
		htmlPath = webRealPath+"/html";
		this.config = config;
		if(config.getInitParameter("htmlPath") != null){
			htmlPath = webRealPath + config.getInitParameter("htmlPath");
		}
		System.out.println("static html path="+htmlPath);
	}

}
